import { ContentState } from 'draft-js';
import React, { useState, useEffect, useRef, CSSProperties, useContext, memo, ReactNode } from 'react';
import EditorContext from '../../../context/EditorContext';
import { getTextWidth, isEmpty, toastShort } from '../../../utils';
import { DeviceEntityRange } from '../../../utils/types';



interface Props {
    contentState: ContentState
    decoratedText: string
    start: number
    end: number
    blockKey: string
    entityKey: string
    children: ReactNode
    offsetKey: string
}

const SpecialTextWithInput = (props: Props) => {

    const {
        onEntityChange,
        getCurrentEntityOffsetWidth,
        setCurrentEntityOffsetWidth
    } = useContext(EditorContext);

    const {
        contentState,
        decoratedText,
        start,
        end,
        blockKey,
        entityKey,
        children,
    } = props;

    const [currentEntity] = useState(contentState.getEntity(entityKey));

    const [currentEntityData, setCurrentEnityData] = useState<DeviceEntityRange>(currentEntity.getData());
    const [value, setValue] = useState('');
    const [initalValue, setInitalValue] = useState('');
    const cacheValue = useRef<string>('');
    const inputRef = useRef(null);
    const measureDivRef = useRef(null);
    const delayTimer = useRef(null);
    const delayTimer1 = useRef(null);
    const textHasBeenEdit = useRef<boolean>(false);
    const cacheLayoutWidth = useRef<number>(0);
    const textValueHasChange = useRef<boolean>(false);

    // const getEntityInlineStyleRange = () => {
    //     const entityRanges = contentBlock.getEntityRanges(character => character.getEntity() === entityKey);
    //     for (const range of entityRanges) {
    //         const { start, end } = range;
          
    //         // 获取所有的 inlineStyleRanges
    //         const inlineStyleRanges = contentBlock.getInlineStyleAt(start, end);
            
    //         // 遍历所有的 inlineStyleRanges
    //         for (const inlineStyleRange of inlineStyleRanges) {
    //           // 检查这个 range 是否在 entity 的范围内
    //           if (inlineStyleRange.start >= start && inlineStyleRange.end <= end) {
    //             // 如果是，那么这个 inlineStyleRange 的样式就是 entity 的样式
    //             console.log('Entity style:', inlineStyleRange.style);
    //           }
    //         }
    //       }
    // }
    
    useEffect(() => {
        // console.log("测试Enitychildren---->", decoratedText, entityKey, props);
        // console.log("测试整个EntityMap---->", contentState.getEntityMap().get(entityKey), contentState.getAllEntities().get(entityKey))
        const entity = contentState.getEntity(entityKey);
        const entityData: DeviceEntityRange = entity.getData();
        // console.log("根据entityKey获取到的------->", entity, entityData, entityData.text)
        // console.log("Entity组件初始化", entityData.text, entityKey)
        const {
            text
        } = entityData;
        const testOffsetWidth = getCurrentEntityOffsetWidth(entityData);
        // console.log("testOffsetWidth---->", testOffsetWidth, text)
        if (testOffsetWidth) {
            cacheLayoutWidth.current = testOffsetWidth;
            inputRef.current.style.width = `${testOffsetWidth}px`;
        }
        if (entityData && !isEmpty(text)) {
            setValue(text);
            setInitalValue(text);
        } else {
            console.log("此时是空的Enity----->")
        }
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current)
            delayTimer1.current && clearTimeout(delayTimer1.current)
        }
    }, [contentState])


    useEffect(() => {
        if (cacheLayoutWidth.current > 0 && cacheLayoutWidth.current > 12 && cacheValue.current == value) {
            // console.log("cacheValue.current--->", cacheValue.current)
            // console.log("直接应用的", cacheLayoutWidth.current)
            inputRef.current.style.width = `${cacheLayoutWidth.current}px`;
            return;
        }
        // console.log("value-------->", value)
        const entity = contentState.getEntity(entityKey);
        let entityData: DeviceEntityRange = entity.getData();
        let layoutWidth = 0;
        if (measureDivRef.current) {
            layoutWidth = measureDivRef.current.offsetWidth - 30;
            if (layoutWidth < 12) {
                layoutWidth = measureDivRef.current.offsetWidth;
            }
            entityData.offsetWidth = layoutWidth;
            cacheLayoutWidth.current = layoutWidth;
            setCurrentEntityOffsetWidth(entityData);
        }
        // console.log("测试layoutWidth", layoutWidth)
        if (layoutWidth) {
            inputRef.current.style.width = `${layoutWidth}px`;
        }
        cacheValue.current = value;
    }, [value, currentEntityData, currentEntityData.text, contentState]);

    const handleChange = (e) => {
        e.stopPropagation();
        if (e.target.value !== value) {
            textHasBeenEdit.current = true;
        }
        let text = e.target.value;
        if(isEmpty(text)){
            return toastShort('error', '文本不能为空')
        }
        if (currentEntityData && currentEntityData.deviceAttributeType == '$[N]') {
            text = text.replace(/[^\d^\.]+/g, '');
            let arr1 = text.split('.');
            if (arr1.length > 2) {
                toastShort('warning', '只能输入一个小数点')
                return false;
            } else {
                if (arr1[1] && arr1[1].length > 2) {
                    toastShort('warning', '只能输入一个小数点后两位数')
                    return false;
                }
            }
        } 
        setValue(text);
    };

    const handleFocus = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleBlur = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        const entity = contentState.getEntity(entityKey);
        const entityData: DeviceEntityRange = entity.getData();
        if(isEmpty(value)){
            setValue(initalValue);
            return toastShort('error', '文本不能为空，已自动重置为上次记录');
        }
        if (textHasBeenEdit.current) {
            onEntityChange && onEntityChange(blockKey, entityKey, entityData, value)
        }
        textHasBeenEdit.current = false;
    };

    const handleKeyDown = (e) => {
        const {
            code,
            key
        } = e;
        if (code === 'Enter') {
            inputRef.current.blur();
            e.preventDefault();
            e.stopPropagation();
        }
        e.stopPropagation();
    };

    const MeasureDivStyle: CSSProperties = {
        position: 'absolute',
        visibility: 'hidden',
        whiteSpace: 'pre',
        fontSize: 'inherit',
        top: 0,
        left: 0,
        pointerEvents: 'none',
        height: 10,
        overflow: 'hidden'
    };

    const handleClick = (e) => {
        e.stopPropagation();
        delayTimer.current = setTimeout(() => {
            inputRef.current.focus();
        }, 0);
    };

    const handleKeyUp = (e) => {
        e.stopPropagation();
    }

    const handleMouseUp = (e) => {
        e.stopPropagation();
    }

    const handleMouseDown = (e) => {
        e.stopPropagation();
    }

    const handleBeforeInput = (e) => {
        e.stopPropagation();
    };

    const handleCompositionEnd = (e) => {
        e.stopPropagation();
    };

    const handleInput = (e) => {
        e.stopPropagation();
    }

    // return (
    //     <div
    //         className='read-only-word-editor-input-container'
    //     >
    //         <span
    //             className='read-only-word-editor-input'
    //             data-offset-key={props.offsetKey}
    //         >
    //             {props.children}+1
    //         </span>
    //     </div>
    // );
    return (
        <>
            <input
                ref={inputRef}
                value={value}
                onChange={handleChange}
                onFocus={handleFocus}
                onBlur={handleBlur}
                // onMouseDown={handleMouseDown}
                onKeyDown={handleKeyDown}
                onBeforeInput={handleBeforeInput}
                onCompositionEnd={handleCompositionEnd}
                onInput={handleInput}
                onKeyUp={handleKeyUp}
                onClick={handleClick}
                onMouseUp={handleMouseUp}
                type="text"
                className='word-editor-input'
            />
            <div
                ref={measureDivRef}
                style={MeasureDivStyle}
            >
                {value || ' '}
            </div>
        </>

    );
};

const checkUpdate = (prevProps: Props, nextProps: Props): boolean => {
    // console.log("prevProps---->", prevProps);
    // console.log("nextProps---->", nextProps);
    let dotNeedUpdate = prevProps.children == nextProps.children;
    return dotNeedUpdate;
}

export default memo(SpecialTextWithInput, checkUpdate);